package com.fick.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * 通用函数类，包括一系列有用的函数，其中大部分时静态函数。
 */

public class General {

	/**
	 * 从属性表中获取某一属性的字符串值
	 * 
	 * @param p
	 *          属性表对象
	 * @param key
	 *          属性名称
	 * @return 属性值
	 */
	public static String consume(Properties p, String key) {
		String s = null;

		if ((p != null) && (key != null)) {
			s = p.getProperty(key);
		}

		return s;
	}

	/**
	 * 从属性表中获取某一属性代表的数值
	 * 
	 * @param p
	 *          属性表对象
	 * @param key
	 *          属性名称
	 * @return 属性代表的数值
	 */
	public static int consumeInt(Properties p, String key) {
		int n = -1;

		String value = consume(p, key);
		if (value != null) {
			try {
				n = Integer.parseInt(value);
			} catch (Exception ex) {
			}
		}

		return n;
	}

	/**
	 * 将java.util.Data类型转化成java.sql.Data
	 * 
	 * @param date
	 *          java.util.Data对象
	 * @return java.sql.Data对象
	 */
	public static java.sql.Date convertDateToSqlDate(Date date) {
		if (date == null) {
			return null;
		} else {
			return new java.sql.Date(date.getTime());
		}
	}

	/**
	 * 将日期转化成字符串，日期的模式为"yyyy年MM月dd日"
	 * 
	 * @param date
	 *          日期对象
	 * @return 表示日期的字符串
	 */
	public static String convertDateToString(Date date) {
		String pattern = "yyyy年MM月dd日";
		return convertDateToString(date, pattern);
	}

	/**
	 * 将日期对象转换成特定模式的字符串
	 * 
	 * @param date
	 *          日期对象
	 * @param pattern
	 *          字符串模式，如：yyyy年M月d日，yyyy-MM-dd等
	 * @return 特定格式的字符串
	 */
	public static String convertDateToString(Date date, String pattern) {
		String str = null;

		if (date == null) {
			return "";
		}

		SimpleDateFormat formatter = new SimpleDateFormat(pattern);
		str = formatter.format(date);

		return str;
	}

	/**
	 * 将java.util.Data类型转化成java.sql.Timestamp
	 * 
	 * @param date
	 *          java.util.Data对象
	 * @return java.sql.Timestamp对象
	 */
	public static java.sql.Timestamp convertDateToTimestamp(Date date) {
		if (date == null) {
			return null;
		} else {
			return new java.sql.Timestamp(date.getTime());
		}
	}

	/**
	 * 将GBK编码格式的字符串转换成ISO编码字符串
	 * 
	 * @param str
	 *          用GBK编码的字符串
	 * @return ISO编码的字符串
	 */
	public static String convertGBKToISO(String str) {
		String convertedStr = null;

		try {
			convertedStr = new String(str.getBytes(), "iso8859-1");
		} catch (Exception _ex) {
			_ex.printStackTrace();
		}

		return convertedStr;
	}

	/**
	 * 将ISO编码格式的字符串转换成GBK编码字符串
	 * 
	 * @param str
	 *          用ISO编码的字符串
	 * @return GBK编码的字符串
	 */
	public static String convertISOToGBK(String str) {
		String convertedStr = null;

		try {
			convertedStr = new String(str.getBytes("iso8859-1"), "GBK");
		} catch (Exception _ex) {
			_ex.printStackTrace();
		}

		return convertedStr;
	}

	/**
	 * 将ISO编码格式的字符串转换成UTF-8编码字符串
	 * 
	 * @param str
	 *          用ISO编码的字符串
	 * @return GBK编码的字符串
	 */
	public static String convertISOToUTF(String str) {
		String convertedStr = null;

		try {
			convertedStr = new String(str.getBytes("iso8859-1"), "UTF-8");
		} catch (Exception _ex) {
			_ex.printStackTrace();
		}

		return convertedStr;
	}

	/**
	 * 将一个链表中的数据作为字符串数组输出
	 * 
	 * @param list
	 *          List 链表
	 * @return String[] 字符串数组
	 */
	public static String[] convertList2StrArray(java.util.List<String> list) {
		String[] strArray = null;

		// 合成新的合并信息
		if (list.size() > 0) {
			int len = list.size();
			strArray = new String[len];
			for (int i = 0; i < len; i++) {
				strArray[i] = list.get(i);
			}
		}

		return strArray;
	}

	/**
	 * 转换字符串，如果值为null,返回""
	 * 
	 * @param str
	 *          字符串
	 * @return 返回经过规整的字符串
	 */
	public static String convertNullToEmpty(String str) {
		String convertedStr = str;
		if (convertedStr == null) {
			convertedStr = "";
		}

		return convertedStr;
	}

	/**
	 * 将字符串中有空格的地方转化成<&nbsp>
	 * 
	 * @param str
	 *          普通字符串
	 * @return 空格经过转化后的字符串s
	 */
	public static String convertNullToHTMLEmpty(String str) {
		String convertedStr = str;
		if (convertedStr == null) {
			convertedStr = "&nbsp";
		}

		return convertedStr;
	}

	/**
	 * 将"yyyy年M月d日"格式的字符串转化成日期
	 * 
	 * @param str
	 *          日期字符串
	 * @return 日期对象
	 * @throws java.text.ParseException
	 */
	public static Date convertStringToDate(String str) throws java.text.ParseException {
		String pattern = "yyyy-MM-DD";
		return convertStringToDate(str, pattern);
	}

	/**
	 * 将特定格式的字符串转化成日期
	 * 
	 * @param str
	 *          日期字符串
	 * @param pattern
	 *          字符串模式，如：yyyy年M月d日，yyyy-MM-dd等
	 * @return 日期对象
	 * @throws java.text.ParseException
	 */
	public static Date convertStringToDate(String str, String pattern) throws java.text.ParseException {
		Date date = null;

		if (str.equals("") || str == null) {
			return date;
		}

		SimpleDateFormat formatter = new SimpleDateFormat(pattern);
		date = formatter.parse(str);

		return date;
	}

	/**
	 * 将字符串转换成double值
	 * 
	 * @param str
	 *          字符串
	 * @return 对应的double值
	 */
	public static double convertStringToDouble(String str) {
		return Double.parseDouble(str);
	}

	/**
	 * 将字符串转换成float值
	 * 
	 * @param str
	 *          字符串
	 * @return 对应的float值
	 */
	public static float convertStringToFloat(String str) {
		return Float.parseFloat(str);
	}

	/**
	 * 将字符串转换成int值
	 * 
	 * @param str
	 *          字符串
	 * @return 对应的int值
	 */
	public static int convertStringToInt(String str) {
		return Integer.parseInt(str);
	}

	/**
	 * 将文本按照HTML的要进行编码
	 * 
	 * @param html
	 *          原始的字符串
	 * @return 转换后的字符串
	 */
	public static String encodeHTML(String source) {
		String html = "";

		Vector<String> v = new Vector<String>();
		// 将长的字符串转化成多个长度为100的短字符串
		int shortStrLen = 100;
		while (source.length() > shortStrLen) {
			String tempStr = source.substring(0, shortStrLen);
			v.add(tempStr);
			source = source.substring(shortStrLen);
		}
		v.add(source);

		for (int i = 0; i < v.size(); i++) {
			String tempStr = (String) v.get(i);
			tempStr = replaceString(tempStr, " ", "&nbsp;");
			tempStr = replaceString(tempStr, "<", "&lt");
			tempStr = replaceString(tempStr, ">", "&gt");
			// tempStr = replaceString(tempStr,"\"", "&quot;");
			tempStr = replaceString(tempStr, "\r\n", "<br>");
			html += tempStr;
		}
		v.clear();
		v = null;

		html = replaceString(html, "\r\n", "<br>");

		return html;
	}

	/**
	 * 将HTML的特有编码转换为文本
	 * 
	 * @return 转换后的字符串
	 */
	public static String encodeText(String source) {
		String html = "";

		Vector<String> v = new Vector<String>();
		// 将长的字符串转化成多个长度为100的短字符串
		int shortStrLen = 100;
		while (source.length() > shortStrLen) {
			String tempStr = source.substring(0, shortStrLen);
			v.add(tempStr);
			source = source.substring(shortStrLen);
		}
		v.add(source);

		for (int i = 0; i < v.size(); i++) {
			String tempStr = (String) v.get(i);
			tempStr = replaceString(tempStr, "&nbsp;", " ");
			tempStr = replaceString(tempStr, "&lt", "<");
			tempStr = replaceString(tempStr, "&gt", ">");
			// tempStr = replaceString(tempStr,"\"", "&quot;");
			tempStr = replaceString(tempStr, "<br>", "\r\n");
			html += tempStr;
		}
		v.clear();
		v = null;

		html = replaceString(html, "<br>", "\r\n");

		return html;
	}

	/**
	 * Function:截取字符串,取得strFrom和strTo之外的内容
	 * 
	 * @param strSource
	 * @param length
	 * @return
	 */
	public static String getSubstr(String strSource) {
		java.lang.String strDest = "";
		int intPos1 = 0, intPos2 = 0;
		String strFrom = "<";
		String strTo = ">";
		while ((intPos1 = strSource.indexOf(strFrom)) != -1) {
			strDest = strDest + strSource.substring(0, intPos1);
			if ((intPos2 = strSource.indexOf(strTo)) != -1) {
				strSource = strSource.substring(intPos2 + 1);
			}
		}
		strDest = strDest + strSource;
		strDest = strDest.replaceAll("&nbsp;", "").replaceAll("&ldquo;", "").replaceAll("&rdquo;", "")
				.replaceAll("&mdash;", "").replaceAll("&hellip;", "").replaceAll("\r\n", "").replaceAll("\n", "")
				.replaceAll("\r", "").replaceAll("　", "").replaceAll(" ", "").trim();
		return strDest;
	}

	/**
	 * 从parameter.ini中读取某一参数的值
	 * 
	 * @param paraName
	 *          参数
	 * @return 参数值
	 */
	public static String getSystemParameter(@SuppressWarnings("rawtypes") Class cls, String paraName) {
		String value = null;
		InputStream in = null;// 配置文件输入流

		try {
			String cfgFileName = "system.ini";

			ClassLoader cl = cls.getClassLoader();
			if (cl != null) {
				in = cl.getResourceAsStream(cfgFileName);
			} else {
				in = ClassLoader.getSystemResourceAsStream(cfgFileName);
			}

			Properties properties = new Properties();
			// 加载到属性中
			properties.load(in);
			value = consume(properties, paraName);
		} catch (Exception _ex) {
			_ex.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}

		return value;
	}

	/**
	 * 取得当天的时间
	 * 
	 * @return 当天的时间
	 */
	public static Date getToday() {
		GregorianCalendar cal = new GregorianCalendar();
		return cal.getTime();
	}

	/**
	 * 默认一个字节一个字节进行传输
	 * 
	 * @param in
	 *          输入流
	 * @param out
	 *          输出流
	 * @throws Exception
	 */
	public static void outputData(InputStream input, OutputStream output) throws Exception {
		int i;
		while ((i = input.read()) != -1) {
			output.write(i);
		}
	}

	/**
	 * 从输入流将数据拷贝到输出流
	 * 
	 * @param in
	 *          输入流
	 * @param out
	 *          输出流
	 * @throws Exception
	 */
	public static void outputData(InputStream input, OutputStream output, int blockSize) throws Exception {
		int streamLen = input.available();
		int blockNums = streamLen / blockSize;
		if ((streamLen % blockSize) > 0) {
			blockNums++;
		}

		// 传输数据
		byte[] b = new byte[blockSize];
		int dataLen = 0;
		for (int i = 0; i < blockNums; i++) {
			dataLen = input.read(b, 0, blockSize);
			output.write(b, 0, dataLen);
			Thread.sleep(2);
		}
	}

	/**
	 * 将指定字符串中的标记用相应的字符串替换掉
	 * 
	 * @param source
	 *          需要替换的字符串
	 * @param tag
	 *          标记
	 * @param value
	 *          替换值
	 * @return 相关标记被替换的字符串
	 */
	public static String replaceString(String source, String tag, String value) {
		String str = "";
		String right = source;
		String left = "";

		int len = tag.length();
		int start = right.indexOf(tag);
		int end = -1;

		while (start != -1) {
			end = start + len;
			left = left + right.substring(0, start) + value;
			right = right.substring(end);
			start = right.indexOf(tag);
		}
		str = left + right;

		return str;
	}

	/**
	 * 将一个以逗号隔开的字符串转化成字符串数组
	 * 
	 * @param str
	 *          String 以逗号隔开的字符串
	 * @return String[] 字符串数组
	 */
	public static String[] split(String str) {
		return split(str, ",");
	}

	/**
	 * 将用指定符号格开的字符串转化成字符串数组
	 * 
	 * @param str
	 *          带有指定符号的字符串
	 * @param delim
	 *          指定符号
	 * @return 对应的字符串数组
	 */
	public static String[] split(String str, String delim) {
		List<String> list = new LinkedList<String>();
		StringTokenizer st = new StringTokenizer(str, delim);

		while (st.hasMoreTokens()) {
			list.add(st.nextToken());
		}

		int len = list.size();
		String[] data = new String[len];

		for (int i = 0; i < len; i++) {
			data[i] = (String) list.get(i);
		}

		return data;
	}

	/**
	 * 截断字符串(按字节截取)
	 * 
	 * @param str
	 * @param length
	 * @return
	 */
	public static String trimStringInLength(String str, int toCount) {
		int reInt = 0;
		String reStr = "";
		if (str == null) {
			return "";
		}

		char[] tempChar = str.toCharArray();
		for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
			String s1 = String.valueOf(tempChar[kk]);
			byte[] b = s1.getBytes();
			reInt += b.length;
			reStr += tempChar[kk];
		}
		if (toCount == reInt || (toCount == reInt - 1)) {
			reStr += "...";
		}
		return reStr;

	}

	/**
	 * 截断字符串(按字符截取)
	 * 
	 * @param str
	 *          被截取的字符
	 * @param length
	 *          截取的长度
	 * @param format
	 *          截取后添加的字符串,通常是"..."
	 * @return
	 */
	public static String trimStringInLength(String str, int toCount, String format) {
		if (str == null) {
			return "";
		}
		if (format == null) {
			format = "";
		}
		if (str.length() > toCount) {
			str = str.substring(0, toCount - 1) + format;
		}
		return str;
	}

	/**
	 * 将一个字符串数组转换成用逗号符隔开的字符串
	 * 
	 * @param str
	 *          String[] 字符串数组
	 * @return String 用逗号符隔开的字符串
	 */
	public static String union(String[] str) {
		return union(str, ",");
	}

	/**
	 * 将一个字符串数组转换成用分隔符隔开的字符串
	 * 
	 * @param str
	 *          String[] 字符串数组
	 * @param delim
	 *          String 分隔符
	 * @return String 用分隔符隔开的字符串
	 */
	public static String union(String[] str, String delim) {
		String unionStr = "";

		if (str != null) {
			for (int i = 0; i < str.length; i++) {
				unionStr += str[i] + delim;
			}

			// 去掉最后一个分隔符
			if (!unionStr.equals("")) {
				unionStr = unionStr.substring(0, unionStr.length() - delim.length());
			}
		}

		return unionStr;
	}
}
